<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人主页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            min-height: 100vh;
        }

        /* 顶部导航栏 */
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px;
            border-bottom: 1px solid #eee;
            position: sticky;
            top: 0;
            background-color: #fff;
            z-index: 10;
        }

        .back-btn {
            font-size: 20px;
            color: #333;
            text-decoration: none;
        }

        .header-title {
            font-weight: 600;
            font-size: 18px;
        }

        .settings-btn {
            font-size: 20px;
            color: #333;
        }

        /* 用户信息区域 */
        .profile-section {
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #fff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 15px;
            cursor: pointer;
        }

        .username {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .user-account {
            color: #888;
            font-size: 14px;
            margin-bottom: 20px;
        }


        .toast-message {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 10px 20px;
            border-radius: 20px;
            z-index: 1000;
            animation: fadeInOut 2s ease-in-out;
        }

        @keyframes fadeInOut {
            0% { opacity: 0; }
            20% { opacity: 1; }
            80% { opacity: 1; }
            100% { opacity: 0; }
        }



        /* 操作按钮区域 */
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }

        .follow-btn, .message-btn {
            padding: 8px 20px;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .follow-btn {
            background-color: #1e88e5;
            color: white;
        }

        .follow-btn:hover {
            background-color: #1565c0;
        }

        .follow-btn.following {
            background-color: #e0e0e0;
            color: #333;
        }

        .message-btn {
            background-color: #fff;
            color: #333;
            border: 1px solid #ddd;
        }

        .message-btn:hover {
            background-color: #f5f5f5;
        }

        .message-btn i {
            margin-right: 5px;
        }

        /* 数据统计区域 */
        .stats-container {
            display: flex;
            justify-content: space-around;
            padding: 15px 0;
            margin: 0 20px;
            border-top: 1px solid #eee;
            border-bottom: 1px solid #eee;
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .stat-label {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
        }

        /* 帖子筛选标签 */
        .tabs {
            display: flex;
            border-bottom: 1px solid #eee;
            margin: 0 20px;
        }

        .tab {
            flex: 1;
            text-align: center;
            padding: 15px 0;
            font-size: 14px;
            color: #666;
            position: relative;
        }

        .tab.active {
            color: #1e88e5;
            font-weight: bold;
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 25%;
            width: 50%;
            height: 3px;
            background-color: #1e88e5;
            border-radius: 3px;
        }

        /* 帖子列表 */
        .posts-container {
            padding: 15px 20px;
        }

        .post-card {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .post-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 8px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .post-content {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .post-meta {
            display: flex;
            align-items: center;
            font-size: 12px;
            color: #999;
        }

        .post-time {
            margin-right: 15px;
        }

        .post-stats span {
            margin-right: 10px;
        }

        .load-more {
            text-align: center;
            padding: 15px;
            color: #1e88e5;
            font-size: 14px;
        }

        button.disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        button.disabled:hover {
            background-color: initial !important;
        }

        /* 私信弹窗 */
        .message-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 100;
            justify-content: center;
            align-items: center;
        }

        .message-content {
            background-color: #fff;
            width: 90%;
            max-width: 400px;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .message-title {
            font-size: 18px;
            font-weight: bold;
        }

        .close-btn {
            font-size: 24px;
            cursor: pointer;
            color: #888;
        }

        .message-input {
            width: 100%;
            height: 100px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            resize: none;
            margin-bottom: 15px;
            font-size: 14px;
        }

        .send-btn {
            width: 100%;
            padding: 10px;
            background-color: #1e88e5;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .send-btn:hover {
            background-color: #1565c0;
        }
    </style>
</head>
<body>
<div class="container" id="app">
    <!-- 顶部导航栏 -->
    <div class="header">
        <a href="#" id="backButton" class="back-btn">←</a>
        <div class="header-title">{{ uname }}的个人主页</div>
        <a href="#" class="settings-btn">⚙️</a>
    </div>

    <!-- 用户信息区域 -->
    <div class="profile-section">
        <img :src="head" alt="用户头像" class="avatar">
        <div class="username">{{ uname }}</div>
        <div class="user-account">{{ bio }}</div>

        <!-- 操作按钮 -->
        <div class="action-buttons" v-if="!isSelf">
            <button class="follow-btn" :class="{ 'following': isFollowing }" @click="toggleFollow">
                {{ isFollowing ? '已关注' : '+ 关注' }}
            </button>
            <button class="message-btn" @click="showMessageModal" :disabled="isSelf">
                <i>💬</i> 私信
            </button>
        </div>
    </div>

    <!-- 数据统计区域 -->
    <div class="stats-container">
        <div class="stat-item">
            <div class="stat-number">{{ counts.follower || 0 }}</div>
            <div class="stat-label">关注</div>
        </div>
        <div class="stat-item">
            <div class="stat-number">{{ counts.following || 0 }}</div>
            <div class="stat-label">粉丝</div>
        </div>
        <div class="stat-item">
            <div class="stat-number">{{ counts.likes || 0 }}</div>
            <div class="stat-label">喜欢</div>
        </div>
        <div class="stat-item">
            <div class="stat-number">{{ counts.posts || 0 }}</div>
            <div class="stat-label">发布</div>
        </div>
    </div>

    <!-- 帖子筛选标签 -->
    <div class="tabs">
        <div class="tab active">全部</div>
        <div class="tab">原创</div>
        <div class="tab">收藏</div>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-container">
        <div class="post-card">
            <div class="post-title">如何快速学习前端开发？我的经验分享</div>
            <div class="post-content">在过去的一年里，我从零开始学习前端开发，现在已经能够独立完成项目。这篇文章将分享我的学习路径、资源推荐和实践经验...</div>
            <div class="post-meta">
                <div class="post-time">2023-05-15</div>
                <div class="post-stats">
                    <span>👍 245</span>
                    <span>💬 36</span>
                </div>
            </div>
        </div>

        <div class="post-card">
            <div class="post-title">周末徒步旅行：探索城市周边的自然风光</div>
            <div class="post-content">上周末我去了城市郊外的青龙山徒步，发现了很多不为人知的美景。这里分享路线图和沿途拍摄的照片，适合一日短途旅行...</div>
            <div class="post-meta">
                <div class="post-time">2023-05-08</div>
                <div class="post-stats">
                    <span>👍 189</span>
                    <span>💬 24</span>
                </div>
            </div>
        </div>

        <div class="post-card">
            <div class="post-title">推荐5本改变我思维方式的好书</div>
            <div class="post-content">阅读是我生活中不可或缺的一部分。今天想和大家分享5本对我的思维方式产生深远影响的书籍，包括心理学、哲学和个人成长领域...</div>
            <div class="post-meta">
                <div class="post-time">2023-04-30</div>
                <div class="post-stats">
                    <span>👍 312</span>
                    <span>💬 42</span>
                </div>
            </div>
        </div>
    </div>

    <div class="load-more">加载更多</div>


<!-- 私信弹窗 -->
    <div class="message-modal" id="messageModal">
        <div class="message-content">
            <div class="message-header">
                <div class="message-title">私信给 {{ uname }}</div>
                <div class="close-btn" id="closeModal">&times;</div>
            </div>
        <textarea class="message-input" placeholder="输入你想发送的私信内容..."></textarea>
        <button class="send-btn">发送</button>
    </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    //从localStorage中获取noteData信息
    const noteData = JSON.parse(localStorage.getItem('noteData'));
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const currentUserId = userInfo.uid || 1;

    new Vue({
        el: '#app',
        data: {
            uname: noteData.author.uname || '未知用户',
            head: noteData.author.head || 'img/boy1.png',
            bio: noteData.author.bio || '这个人很懒，什么也没说...',
            isFollowing: false,
            isSelf: false, // 新增是否是自己标志
            counts: {
                following: 0,
                follower: 0,
                likes: 0,
                posts: 0
            },
            profileUserId: noteData.author.uid || 0,
        },
        created(){
            // 先调用API获取真实的关注状态
            this.loadFollowStatus();
            this.loadCounts();

            this.isSelf = this.profileUserId === currentUserId;
            // 如果是自己，直接隐藏操作按钮
            if (this.isSelf) {
                document.querySelector('.action-buttons').style.display = 'none';
            }

            // 如果API请求失败或未完成，再使用localStorage的缓存状态
            const savedFollowStatus = localStorage.getItem(`followStatus_${this.profileUserId}`);
            if (savedFollowStatus !== null) {
                // 设置初始状态为false，等待API响应
                this.isFollowing = false;
            }
        },
        methods: {
            // 加载关注状态
            loadFollowStatus() {
                if (!this.profileUserId) return;

                axios.get(`/lv-user/follow/status/${currentUserId}/${this.profileUserId}`)
                    .then(response => {
                        // 确保API返回的是布尔值
                        const isFollowing = Boolean(response.data);
                        this.isFollowing = isFollowing;
                        // 更新localStorage
                        localStorage.setItem(`followStatus_${this.profileUserId}`, isFollowing);
                    })
                    .catch(error => {
                        console.error('获取关注状态失败:', error);
                        // API失败时，使用localStorage的缓存状态
                        const savedFollowStatus = localStorage.getItem(`followStatus_${this.profileUserId}`);
                        if (savedFollowStatus !== null) {
                            this.isFollowing = JSON.parse(savedFollowStatus);
                        }
                    });
            },

            // 加载关注数和粉丝数
            loadCounts() {
                if (!this.profileUserId) return;
                console.log('正在加载统计数据，用户ID:', this.profileUserId);

                axios.get(`/lv-user/follow/stats/${this.profileUserId}`)
                    .then(response => {
                        console.log('API响应数据:', response.data);
                        // 根据实际API返回的数据结构调整
                        this.counts.following = response.data.followingCount || response.data.following_count || 0;
                        this.counts.follower = response.data.followerCount || response.data.follower_count || 0;
                    })
                    .catch(error => {
                        console.error('获取统计数据失败:', error);
                        this.counts.following = 0;
                        this.counts.follower = 0;
                    });
            },

            // 切换关注状态
            toggleFollow() {
                if (!this.profileUserId) return;

                // 新增自我关注检测
                if (this.profileUserId === currentUserId) {
                    this.showToast('不能关注自己');
                    return;
                }

                const action = this.isFollowing ? 'unfollow' : 'follow';

                if (action === 'unfollow') {
                    // 修改取消关注的请求方式
                    axios.delete(`/lv-user/follow/${currentUserId}/${this.profileUserId}`, {
                        params: {
                            followerId: currentUserId,
                            followingId: this.profileUserId
                        }
                    })
                        .then(() => {
                            this.isFollowing = false;
                            localStorage.removeItem(`followStatus_${this.profileUserId}`);
                            this.showToast('已取消关注');
                            this.loadCounts();
                        })
                        .catch(error => {
                            console.error('取消关注失败:', error);
                            // 更详细的错误处理
                            if (error.response) {
                                if (error.response.status === 500) {
                                    this.showToast('服务器错误，请稍后再试');
                                } else {
                                    this.showToast(`取消关注失败: ${error.response.status}`);
                                }
                            } else {
                                this.showToast('网络错误，请检查连接');
                            }
                        });
                } else {
                    // 关注逻辑保持不变
                    const followData = {
                        followerId: currentUserId,
                        followingId: this.profileUserId,
                        status: 1,
                        time: new Date().toISOString()
                    };

                    axios.post('/lv-user/follow/add', followData)
                        .then(() => {
                            this.isFollowing = true;
                            localStorage.setItem(`followStatus_${this.profileUserId}`, true);
                            this.showToast('关注成功');
                            this.loadCounts();
                        })
                        .catch(error => {
                            console.error('关注失败:', error);
                            this.showToast('关注失败');
                        });
                }
            },

            // 显示消息提示
            showToast(message) {
                const toast = document.createElement('div');
                toast.className = 'toast-message';
                toast.textContent = message;
                document.body.appendChild(toast);

                setTimeout(() => {
                    toast.remove();
                }, 2000);
            },

            // 显示私信弹窗
            showMessageModal() {
                if (this.isSelf) {
                    this.showToast('不能给自己发送私信');
                    return;
                }
                // 之前的私信弹窗逻辑
                const messageModal = document.getElementById('messageModal');
                messageModal.style.display = 'flex';
            }
        }
    });

    // 保持原有的DOMContentLoaded事件监听
    document.addEventListener('DOMContentLoaded', function() {
        // 获取返回按钮并添加事件监听
        const backButton = document.getElementById('backButton');
        backButton.addEventListener('click', function(e) {
            e.preventDefault();
            if (history.length > 1) {
                history.back();
            } else {
                window.location.href = '/lv-index/index/readmore.html';
            }
        });

        // 私信功能
        const messageBtn = document.querySelector('.message-btn');
        const messageModal = document.getElementById('messageModal');
        const closeModal = document.getElementById('closeModal');
        const sendBtn = document.querySelector('.send-btn');

        // 打开私信弹窗
        messageBtn.addEventListener('click', function() {
            messageModal.style.display = 'flex';
        });

        // 关闭私信弹窗
        closeModal.addEventListener('click', function() {
            messageModal.style.display = 'none';
        });

        // 点击弹窗外部关闭
        messageModal.addEventListener('click', function(e) {
            if (e.target === messageModal) {
                messageModal.style.display = 'none';
            }
        });

        // 发送私信
        sendBtn.addEventListener('click', function() {
            const messageInput = document.querySelector('.message-input');
            const message = messageInput.value.trim();
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const noteData = JSON.parse(localStorage.getItem('noteData'));

            // 新增自我私信检测
            if (userInfo.uid === noteData.author.uid) {
                const toast = document.createElement('div');
                toast.className = 'toast-message';
                toast.textContent = '不能给自己发送私信';
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 2000);
                return;
            }

            if (message && userInfo && noteData) {
                // 构造消息数据
                const messageData = {
                    sid: userInfo.uid,
                    rid: noteData.author.uid,
                    content: message,
                    read: 0
                };

                // 发送消息请求
                fetch('/lv-other/message/send', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(messageData)
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 1) {
                            // 更新本地存储触发信息界面更新
                            localStorage.setItem('messageUpdateTrigger', Date.now());

                            // 关闭弹窗并清空输入
                            messageInput.value = '';
                            messageModal.style.display = 'none';

                            // 显示发送成功提示
                            const toast = document.createElement('div');
                            toast.className = 'toast-message';
                            toast.textContent = '私信发送成功';
                            document.body.appendChild(toast);
                            setTimeout(() => toast.remove(), 2000);
                        } else {
                            alert('发送失败: ' + result.msg);
                        }
                    })
                    .catch(error => {
                        console.error('发送失败:', error);
                        alert('发送失败，请检查网络连接');
                    });
            } else {
                alert('请输入有效的私信内容');
            }
        });
    });
</script>
</body>
</html>